package com.lxl.microservicesimleconsumermovie.controller;

import com.lxl.microservicesimleconsumermovie.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


/**
 * @desc: Movie controller
 * @author: lxl
 * @date: 2018/11/9 16:01
 * @version: v1.0
 */
@RestController
public class MovieController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * @desc: 从用户服务获得信息
     * @author: lxl
     * @date: 2018/11/15 9:55
     * @version: v1.0
     */
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id) {
        return this.restTemplate.getForObject("http://microservice-provider-user-my-metadata/" + id, User.class);
    }

    /**
     * @desc: 获取指定服务的元数据
     * @author: lxl
     * @date: 2018/11/15 9:54
     * @version: v1.0
     */
    @GetMapping("/user-instance")
    public List<ServiceInstance> showInfo() {
        ServiceInstance instance = this.loadBalancerClient.choose("microservice-provider-user-my-metadata");
        if (instance != null) {
            logger.info("{}:{}:{}", instance.getServiceId(), instance.getHost(), instance.getPort());
        }
        return this.discoveryClient.getInstances("microservice-provider-user-my-metadata");
    }
}
